package com.junjiao.util.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * HTML工具
 * 
 * @author jiaojun
 *         <p>
 *         email:junjiao.j@gmail.com
 *         </p>
 * @version v0.0.1
 * @date 2011-5-17
 */
public class HTMLUtil {

	// >
	public static final String GT = "&gt;";
	// <
	public static final String LT = "&lt;";
	// "
	public static final String QUOT = "&quot;";
	// “
	public static final String LQUOT = "&ldquo;";
	// ”
	public static final String RQUOT = "&rdquo;";
	// &
	public static final String AMP = "&amp;";
	// 空格
	public static final String SPACE = "&nbsp;";
	// ©
	public static final String COPYRIGHT = "&copy;";
	// ®
	public static final String REG = "&reg;";
	// ™
	public static final String TM = "&trade;";
	// ¥
	public static final String RMB = "&yen;";
	

	/**
	 * 删除script标签
	 * 
	 * @param str
	 * @return
	 */
	public static String delScriptTag(String str) {
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>";
		Pattern p_script = Pattern.compile(regEx_script,
				Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(str);
		str = m_script.replaceAll("");
		return str.trim();
	}

	/**
	 * 删除style标签
	 * 
	 * @param str
	 * @return
	 */
	public static String delStyleTag(String str) {
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";
		Pattern p_style = Pattern
				.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(str);
		str = m_style.replaceAll("");
		return str;
	}

	/**
	 * 删除HTML标签
	 * 
	 * @param str
	 * @return
	 */
	public static String delHTMLTag(String str) {
		String regEx_html = "<[^>]+>";
		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(str);
		str = m_html.replaceAll("");
		str = str.replaceAll("\">", "");
		return str;
	}

	/**
	 * 删除SQL关键词
	 * 
	 * @param str
	 * @return
	 */
	public static String delSQLTag(String str){
		 str = str.toLowerCase();//统一转为小写
		 String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"  
	            + "(\\b(select|like|update|and|or|delete|drop|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|sleep)\\b)";
		 Pattern p_sql = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		 Matcher m_html = p_sql.matcher(str);
		 str = m_html.replaceAll("");
		 return str;
	}
	
	/**
	 * 删除所有标签(script、style、HTML)
	 * 
	 * @param str
	 * @return
	 */
	public static String delAllTag(String str) {
		// 删script
		str = delScriptTag(str);
		// 删style
		str = delStyleTag(str);
		// 删HTML
		str = delHTMLTag(str);
		// 删除SQL关键词L
		str = delSQLTag(str);
		return str;
	}

	/**
	 * 清除标签,恢复HTML转义字符
	 * 
	 * @param str
	 * @return
	 */
	public static String clean(String str) {
		str = delAllTag(str);
		str = str.replaceAll(SPACE, " ");
		str = str.replaceAll(GT, ">");
		str = str.replaceAll(LT, "<");
		str = str.replaceAll(QUOT, "\"");
		str = str.replaceAll(AMP, "&");
		str = str.replaceAll(COPYRIGHT, "©");
		str = str.replaceAll(REG, "®");
		str = str.replaceAll(TM, "™");
		str = str.replaceAll(RMB, "¥");
		str = str.replaceAll(LQUOT, "“");
		str = str.replaceAll(RQUOT, "”");
		
		return str;
	}

	/**
	 * 过滤指定标签
	 * 
	 * @param str
	 * @param tag
	 *            指定标签
	 * @return String
	 */
	public static String fiterHtmlTag(String str, String tag) {
		String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
		Pattern pattern = Pattern.compile(regxp);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 替换指定的标签
	 * 
	 * @param str
	 * @param beforeTag
	 *            要替换的标签
	 * @param tagAttrib
	 *            要替换的标签属性值
	 * @param startTag
	 *            新标签开始标记
	 * @param endTag
	 *            新标签结束标记
	 * @return String example: 替换img标签的src属性值为[img]属性值[/img]
	 */
	public static String replaceHtmlTag(String str, String beforeTag,
			String tagAttrib, String startTag, String endTag) {
		String regxpForTag = "<\\s*" + beforeTag + "\\s+([^>]*)\\s*>";
		String regxpForTagAttrib = tagAttrib + "=\"([^\"]+)\"";
		Pattern patternForTag = Pattern.compile(regxpForTag);
		Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
		Matcher matcherForTag = patternForTag.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result = matcherForTag.find();
		while (result) {
			StringBuffer sbreplace = new StringBuffer();
			Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag
					.group(1));
			if (matcherForAttrib.find()) {
				matcherForAttrib.appendReplacement(sbreplace, startTag
						+ matcherForAttrib.group(1) + endTag);
			}
			matcherForTag.appendReplacement(sb, sbreplace.toString());
			result = matcherForTag.find();
		}
		matcherForTag.appendTail(sb);
		return sb.toString();
	}

	/**
     * 将img标签中的src进行二次包装,并将指定的宽高去掉 
     * 		<img src=\"http://picture.51auto.com/info/info20120612144045.jpg\" width=\"442\" height=\"291\" /> <input src=\"http://picture.51auto.com/info/info20120612144045.jpg\" width=\"442\" height=\"291\" type=\"image\" /><br>
     * 
     * @param content 需要替换内容
     * @param newURL 新图片地址
     * @return
     */
    protected String repairContent(String content,String newURL) {
	// 1 处理img类型的标签
	String patternStr = "<img\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";
	Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
	Matcher matcher = pattern.matcher(content);
	String result = content;
	while (matcher.find()) {
	    String src = matcher.group(2);
	    result = result.replaceAll(src, newURL);
	}

	result = result.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
	result = result.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");

	// 2 处理input类型的img标签
	patternStr = "<input\\s*([^>]*)\\s*src=\\\"(.*?)\\\"\\s*([^>]*)>";
	pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
	matcher = pattern.matcher(result);
	while (matcher.find()) {
	    String src = matcher.group(2);
	    result = result.replaceAll(src, newURL);
	}

	result = result
		.replaceAll("(<input[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
	result = result.replaceAll("(<input[^>]*?)\\s+height\\s*=\\s*\\S+",
		"$1");
	return result;
    }

    /**
	 * 通过freemarker生成静态页面 
	 * @param data 一个Map的数据结果集
	 * @param templatePath   ftl模版路径
	 * @param targetHtmlPath 生成静态页面的路径
	 * @see 
	 * <p>
	 * public void makeFriendLink(){  <br>
	 * 	FriendLink fl = new FriendLink(); <br>
	 * 	fl.setType(FriendLink.TYPE_GZ_1671); <br>	 	
	 * 	List<FriendLink> list = friendLinkDao.queryFriendLink(fl); <br>
	 * 	if (list != null && list.size() > 0) { <br>
	 * 		String temppath = "/WEB-INF/templates/qa/makePage/indexFriendLink.ftl"; <br>
	 * 		String htmlpath = "/static/qa/web/cache/indexFriendLink.html"; <br>
	 * 		Map<String, Object> map = new HashMap<String, Object>(); <br>
	 * 		map.put("objs", list); <br>
	 * 		crateHTML(map, temppath, htmlpath);	 <br>		
	 * 	} <br>
	 * } <br>
	 * </p>
	 */
//	public static void crateStaticHTML(Map<String, Object> data, String templateName, String htmlName) {
//		Configuration freemarkerCfg = new Configuration();
//		// 设置模版		
//		freemarkerCfg.setDefaultEncoding("UTF-8");
//		
//		//模版路径
//		String htmlFileName = FileUtil.FilePath+htmlName;		
//		try {
//			// 指定模版路径
//			freemarkerCfg.setDirectoryForTemplateLoading(new File(FileUtil.FilePath));
//			freemarkerCfg.setDateFormat("yyyy-MM-dd hh:mm");
//			freemarkerCfg.setNumberFormat("#########");
//			Template template = freemarkerCfg.getTemplate(templateName, "UTF-8");
//			template.setEncoding("UTF-8");
//			File htmlFile = new File(htmlFileName);
//			Writer out = new BufferedWriter(new OutputStreamWriter(
//					new FileOutputStream(htmlFile), "UTF-8"));
//			// 处理模版			
//			template.process(data, out);
//			out.flush();
//			out.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}
